<template>
    <div id="orglist">
      <!-- <Breadcrumb :content="$store.state.curMenu.leftMenuName" v-if="!isChildren" /> -->
  
      <vxe-toolbar perfect ref="toolbarRef">
        <template #buttons>
          <vxe-input
            style="width: 130px"
            v-model="orgForm.searchValue"
            clearable
            placeholder="关键字查询"
            type="search"
            @clear="findOrgList"
            @keyup.enter.native="handleSearch(orgForm.searchValue)"
            @search-click="handleSearch(orgForm.searchValue)"
          >
          </vxe-input>
          <vxe-button
            type="text"
            status="primary"
            icon="vxe-icon-refresh"
            content="刷新"
            @click="findOrgList"
          ></vxe-button>
          <vxe-button
            type="text"
            status="success"
            icon="vxe-icon-square-plus"
            content="新建"
            @click="addOrg('','')"
          ></vxe-button>
          <vxe-button
            type="text"
            status="success"
            icon="vxe-icon-save"
            content="保存"
            @click="saveOrg"
          ></vxe-button>
          <vxe-button
            type="text"
            status="success"
            icon="vxe-icon-sort"
            content="同步数据"
            @click="pullOrg"
          ></vxe-button>
        </template>
      </vxe-toolbar>
  
      <!-- height: isChildren ? 'calc(100% - 40px)' : 'calc(100% - 40px - 40px)' -->
      <!-- v-loading="tloading" -->
      <!-- @edit-closed="handleEditClosed" -->
      <!-- @keydown.enter.native="handleEditClosed" -->
      
      <div class="tableBox" style="height: calc(100vh - 80px)">
        <vxe-table
          ref="orgTable"
          border
          :data="orgaList"
          height="auto"
          :expand-config="{ expandAll: true, reserve: true }"
          @current-change="orgRowClick"
          :row-config="{ isCurrent: true, isHover: true }"
          :column-config="{ resizable: true }"
          :keyboard-config="{
            isArrow: true,
            isTab: true,
            isEdit: true
          }"
          :tree-config="{
            expandAll: true,
            transform: true,
            rowField: 'id',
            parentField: 'parentId'
          }"
          :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }"
          resizable
          show-overflow
          keep-source
        >
          <!-- <vxe-column type="checkbox" width="26"></vxe-column> -->
          <vxe-column field="code" title="编码" width="120" tree-node :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input type="text" :underline="false" v-model="row.code"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="name" title="名称" min-width="110" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input type="text" :underline="false" v-model="row.name"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column title="操作" width="60" align="center" fixed="right">
            <template #default="{ row }">
              <el-tooltip class="item" effect="dark" content="新建子分组" placement="left">
                <vxe-button
                  type="text"
                  status="primary"
                  icon="vxe-icon-square-plus"
                  circle
                  @click.native="addOrg(row.id, row)"
                >
                </vxe-button>
              </el-tooltip>
              <vxe-button
                type="text"
                status="danger"
                icon="vxe-icon-delete"
                circle
                @click.native="deleteOrg(row.id)"
              ></vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, getCurrentInstance, nextTick } from 'vue';
  import Breadcrumb from '@/components/Breadcrumb.vue';
  import { Splitpanes, Pane } from 'splitpanes';
  let { proxy }: any = getCurrentInstance();
  import { pageSizes, notifyType, notifyMessage } from '../../utils/common';
  import { rowContextKey } from 'element-plus';
  // import { findIndex } from 'lodash';
  import { VXETable } from 'vxe-table';
  
  let orgForm = {
    id: '',
    parentId: null,
    parentName: '',
    name: '',
    code: '',
    tenantId: null,
    //用户输入查询内容
    searchValue: ''
  };
  let orgFormRule = {
    name: [
      {
        required: true,
        message: '请输入机构名称',
        trigger: 'blur'
      },
      {
        min: 2,
        max: 20,
        message: '长度为2到20个字符',
        trigger: 'blur'
      }
    ]
  };
  
  let isChildren = ref(false);
  let tloading = ref(false); //加载状态
  
  let toolbarRef = ref(); //查询刷新新建保存同步数据工具栏（没用)
  let orgTable = ref(); //机构表格
  
  
  
  let orgaList: any = reactive([]); //机构列表数据
  let currentOrg = {} as any; //当前机构
  
  // 页面加载时更新组织机构列表(左侧)
  findOrgList();
  
  // 获取机构列表(默认获得全部)
  function findOrgList() {
    tloading.value = true;
    orgaList.length = 0;
    const $table = orgTable.value;
    if ($table) {
      $table.setAllRowExpand(true);
    }
  
    const url = '/api/sys/findOrganizationPageList';
    proxy.$http
      //注意此处的数据条数
      .get(url, { params: { pageIndex: 1, pageSize: 50 } })
      .then((res: any) => {
        // console.log(res.data.orgList);
        orgaList.push(...res.data.records);
        // console.log('机构数据', orgaList);
        // if(proxy.isChildren){
        orgRowClick({ row: orgaList[0] });//默认选中第一条数据
        // }
        const $table = orgTable.value;
        // $table.loadData(orgaList,true);
        tloading.value = false;
      })
      .catch((err: any) => {
        tloading.value = false;
        console.log(err);
        proxy.$alert(err, '提示');
      });
  }
  
  // 查询/刷新
  function handleSearch(row: string | number) {
    tloading.value = true;
    orgaList.length = 0;
    const $table = orgTable.value;
    if ($table) {
      $table.setAllRowExpand(true);
    }
    const url = '/api/sys/findOrganizationPageList';
    proxy.$http
      .get(url, { params: { keywords: row, pageIndex: 1, pageSize: 10 } })
      .then((res: any) => {
        orgaList.push(...res.data.records);
        // console.log(orgaList);
        // if(proxy.isChildren){
        //   orgRowClick({row: this.orgaList[0]})
        // }
        const $table = orgTable.value;
        $table.loadData(orgaList, true);
        tloading.value = false;
      })
      .catch((err: any) => {
        tloading.value = false;
        console.log(err);
        proxy.$alert(err, '提示');
      });
  }
  
  // 清空搜索条件
  function clearForm() {
    orgForm = {
      id: '',
      parentId: null,
      parentName: '',
      name: '',
      code: '',
      tenantId: null,
      //用户输入查询内容
      searchValue: ''
    };
  }
  
  // 查询清空(未使用)
  function handleClear() {
    orgForm.searchValue = '';
    findOrgList();
  }
  
  // 同步数据
  function pullOrg() {}
  
  // 点击机构当前行触发的事件
  function orgRowClick({ row }: any) {
    currentOrg.value = row.value;
    console.log('当前行机构触发的', row);
    proxy.$emit('getCurrentOrg', row);
    if (IsEmpty(row)) {
      return;
    }
    (proxy.$refs.orgTable as any).setCurrentRow(row);
  }
  
  //**判断为空*/
  function IsEmpty(value: any) {
    if (value === undefined || value === '' || value === null) {
      return true;
    }
    if (JSON.stringify(value) === '{}') {
      return true;
    }
    return false;
  }
  
  // 离开时触发 进行调用接口
  function handleEditClosed({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }: any) {
    // console.log('KKKKKKKKKKKKK', row, rowIndex, $rowIndex, column, columnIndex, $columnIndex);
    // // id不为空就走修改，id为空就走add
    // const url = row.id != '' && row.id != null ? '/api/sys/editOrg' : '/api/sys/addOrg';
    // proxy.$http
    //   .post(url, row)
    //   .then((res: any) => {
    //     console.log(res.data);
    //   })
    //   .catch((err: any) => {
    //     notifyMessage(err, notifyType.warning, proxy);
    //   });
  }
  
  // 新建一级机构/子结构
  async function addOrg(parentids: any, row:any): Promise<void> {
    //clearForm();
    const $table = orgTable.value;
    if ($table) {
      // 获取新增的数据记录
      const record = {
        code: '',
        name: '',
        parentId: parentids != '' || parentids != null ? parentids : null,
        id: ''
      };
      // orgaList.push(record);
  
      $table.loadData(orgaList);
      const { row: newRow } = await $table.insertAt(record, -1);
  
      // console.log('表格对象', $table, orgaList);
      // 设置编辑行
      // console.log('biaoge', orgaList);
  
      await $table.setEditRow(record);
      if (row) {
        await $table.setTreeExpand(row, true); // 新建一行空数据时展开这一栏
      }
    }
  }
  
  // 保存
  async function saveOrg() {
    const $table = orgTable.value;
    if ($table) {
      const updateRecords = await $table.getUpdateRecords().filter((p: any) => {
        return p.id !== '';
      });
  
      const InsertRecords = await $table.getInsertRecords().filter((m: any) => {
        return m.id === '';
      });
  
      // 修改机构
      updateRecords.forEach((e: any) => {
        const url = '/api/sys/editOrg';
        const tOrganization = e;
        proxy.$http
          .post(url, tOrganization)
          .then((res: any) => {
            // console.log('修改机构', res.data);
            findOrgList()
          })
          .catch((err: any) => {
            notifyMessage(err, notifyType.warning, proxy);
          });
      });
  
      // 新增机构
      InsertRecords.forEach((ele: any) => {
        const url = '/api/sys/addOrg';
        const tOrganization = ele;
        // console.log('新增', tOrganization);
        proxy.$http
          .post(url, tOrganization)
          .then((res: any) => {
            // console.log('新增机构', res.data);
            findOrgList()
          })
          .catch((err: any) => {
            notifyMessage(err, notifyType.warning, proxy);
          });
      });
    }
  }
  
  // 删除部门
  function deleteOrg(id: any) {
    // console.log('要删除的数据', id);
    proxy
      .$confirm('确定删除此组织机构？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const url = '/api/sys/deleteOrgOrDept/' + id;
        proxy.$http.delete(url).then((res: any) => {
          // console.log(res);
          if (res.status.code != 1) {
            proxy.$alert(res.status.msg, '提示');
            // notifyMessage('删除失败', notifyType.warning,res.status.msg);
          } else {
            proxy.$alert(res.status.msg, '提示');
            // notifyMessage('删除成功', notifyType.success, proxy);
          }
          findOrgList();
          // console.log('删除后的数据', orgaList);
        });
      })
      .catch((err: any) => {
        console.log(err);
        proxy.$alert(err, '提示');
      });
  }
  </script>
  
  <style lang="scss" scoped>
  #orglist {
    height: 100%;
    .vxe-toolbar {
      .vxe-button {
        // padding: 0.1em 0;
      }
    }
    .el-divider--vertical {
      height: 20px;
    }
  
    .vxe-table {
      .vxe-button {
        height: auto;
        min-width: auto;
        padding: 0.35em;
        margin-left: 0;
        font-size: 13px;
      }
      [class*=' el-icon-'],
      [class^='el-icon-'],
      [class^='icon-'] {
        font-size: 1.3em;
      }
    }
  }
  </style>
  